package com.mylogistics.common.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.*;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("wxchat")
public class ChatController {

    @Autowired
    private WxMpService wxService;

    @GetMapping(value = "/core")
    public String checkSignature(
            @RequestParam String signature,
            @RequestParam String timestamp,
            @RequestParam String nonce,
            @RequestParam String echostr) {
        boolean flag = wxService.checkSignature(timestamp, nonce, signature);
        if (flag) {
            return echostr;
        }
        return "fail";
    }

    @Autowired
    WxMpConfigStorage configStorage;

    @PostMapping(value = "/core")
    public String core(
            String signature,
            String timestamp,
            String nonce,
            String echostr,
            String encrypt_type,
            HttpServletRequest request
    ) throws IOException, WxErrorException {
        //验证签名是否正确
        boolean flag = wxService.checkSignature(timestamp, nonce, signature);
        if (!flag) {
            throw new RuntimeException("非法操作");
        }
        //是否加密
        String encryptType = StringUtils.isBlank(encrypt_type) ? "raw" : encrypt_type;

        if ("raw".equals(encryptType)) {
            //受到用户发送的消息
            //没有加密
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
            String messageType = inMessage.getMsgType();   //获取类型
            //微信用户
            String fromUser = inMessage.getFromUser();
            //服务器
            String touser = inMessage.getToUser();

            //内容
            String content = inMessage.getContent();

            System.out.println("收到：" + fromUser + "的消息:" + content);


            WxMpXmlOutMessage outMessage = null;
            File file;
            InputStream inputStream;
            WxMediaUploadResult result;
            //返回消息
            //自定义实现相关的业务逻辑
            StringBuffer backSb = new StringBuffer();
            if (content != null) {
                switch (content) {
                    case "1":
                        backSb.append("在吗");
                        break;
                    case "2":
                        backSb.append("你在干什么");
                        break;
                    case "3":
                        backSb.append("我今天不开心");
                        break;
                    default:
                        backSb.append("嘿嘿");
                        break;
                }
                outMessage = WxMpXmlOutTextMessage.TEXT()
                        .content("收到消息了，正在处理\n" + backSb.toString())
                        .fromUser(touser)
                        .toUser(fromUser).build();
            } else {
                switch (messageType){
                        case "voice":
                            file = new File("e:\\222.mp3");
                            inputStream = new FileInputStream(file);
                            result = wxService.getMaterialService().mediaUpload(WxConsts.MediaFileType.VOICE, "mp3", inputStream);
                            outMessage = WxMpXmlOutVoiceMessage.VOICE()
                                    .mediaId(result.getMediaId())
                                    .fromUser(touser)
                                    .toUser(fromUser).build();
                            break;
                        case "image":
                            file = new File("e:\\111.jpg");
                            inputStream = new FileInputStream(file);
                            result = wxService.getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, "jpg", inputStream);

                            outMessage = WxMpXmlOutImageMessage.IMAGE()
                                    .mediaId(result.getMediaId())
                                    .fromUser(touser)
                                    .toUser(fromUser).build();
                            break;
                        case "video":
                            file = new File("e:\\333.MP4");
                            inputStream = new FileInputStream(file);
                            result = wxService.getMaterialService().mediaUpload(WxConsts.MediaFileType.VIDEO, "mp4", inputStream);

                            outMessage = WxMpXmlOutVideoMessage.VIDEO()
                                    .mediaId(result.getMediaId())
                                    .fromUser(touser)
                                    .toUser(fromUser).build();
                            break;
                        default:
                            backSb.append("不好意思，无法识别你的文件类型");
                            outMessage = WxMpXmlOutTextMessage.TEXT()
                                    .content("收到消息了，正在处理\n" + backSb.toString())
                                    .fromUser(touser)
                                    .toUser(fromUser).build();
                            break;
                    }
            }
            return outMessage.toXml();
        }
        if ("aes".equals(encryptType)) {
            // aes加密内容
            String msgSignature = request.getParameter("msg_signature");

            //解密消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(
                    request.getInputStream(), this.configStorage, timestamp, nonce,
                    msgSignature);
            String messageType = inMessage.getMsgType();
            String fromUser = inMessage.getFromUser();
            String touser = inMessage.getToUser();
            String content = inMessage.getContent();

            WxMpXmlOutTextMessage outMessage =
                    WxMpXmlOutTextMessage.TEXT()
                            .content("收到加密消息了")
                            .fromUser(touser)
                            .toUser(fromUser).build();
            //加密返回消息
            return outMessage.toEncryptedXml(this.configStorage);
        }

        return "不支持的类型";
    }
}
